package org.lotic.ldk.string;

import java.security.MessageDigest;

/**
 * 字符串处理常用工具方法.
 * 
 * @author lotic
 * 
 */
public class StringUtil {
	private static final String[] hexDigits =
		{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };
	/**
	 * 检测字符串是否是空串.
	 * 
	 * @param str
	 * @return
	 */
	public static final boolean isEmptyOrNull(String str) {
		return str == null || str.trim().length() == 0;
	}

	/**
	 * 检测是否不为空字符串.
	 * 
	 * @param str
	 * @return
	 */
	public static final boolean isNotEmptyOrNull(String str) {

		return str != null && str.trim().length() > 0;
	}

	/**
	 * 将字符串第一个字母大写
	 * 
	 * @param str
	 *            源字符串
	 * @return 第一个字母大写的字符串.
	 */
	public static final String toUpperCaseFirst(String str) {
		if (StringUtil.isEmptyOrNull(str)) {
			return str;
		} else {
			return str.replaceFirst(str.substring(0, 1), str.substring(0, 1)
					.toUpperCase());
		}

	}
	
	
	/**
	 * MD5加密.16进制字符串.
	 * @param origin
	 * @return
	 */
	public static String encryptMD5Hex(String origin) {
		String resultString = null;
		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
		return resultString;
	}
	
	private static String byteArrayToHexString(byte[] b) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i])); // 若使用本函数转换则可得到加密结果的16进制表示，即数字字母混合的形式

		}
		return resultSb.toString();
	}
	
	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0) {
			n = 256 + n;
		}
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}
	

}
